package cn.xchats.rpc.common.core;

import cn.xchats.rpc.common.annotation.RpcReference;
import cn.xchats.rpc.common.annotation.RpcService;
import cn.xchats.rpc.common.dto.BeanMethod;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Map;

/*
 *中介服务
 * 每个bean实例化的时候 都会执行当前class
 *@author teddy
 *@date 2018/6/29
 */
//@Component
@Deprecated
public class Mediator implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();

        Field[] beanFieldArray = beanClass.getDeclaredFields();
        for (int i = 0; i < beanFieldArray.length; i++) {
            Field field = beanFieldArray[i];
            if (field.isAnnotationPresent(RpcReference.class)) {
                field.setAccessible(true);
                //proxy
                Enhancer enhancer = new Enhancer();
                //设置proxy实现的接口
                enhancer.setInterfaces(new Class[]{field.getType()});
                //拦截方法
                enhancer.setCallback((MethodInterceptor) (instance, method, args, proxy) -> {
                    String methodParameter = Invoke.convertMethodParameter(instance.getClass(), method);

                    return null;
                });
            }
        }


        return null;
    }

    /**
     * 初始化完bean之后执行该方法
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean.getClass().isAnnotationPresent(RpcService.class)) {
            Map<String, BeanMethod> beanMethodMap = Invoke.generateInterfaceInfo(bean);
            CacheBeanMethod.beanMap.putAll(beanMethodMap);
        }

        return null;
    }

}
